import { Component, OnDestroy  } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { InitService } from '@core/services/init.service';
import { UserAuthService } from '@core/services/user-auth.service';
import { ApiService } from '@core/services/http/api.service';
import { ReuseTabService } from '@shared/apes/reuse-tab';
import { ApesMessageService } from '@shared/apes/message';
import { WebsocketService } from '@core/services/websocket/websocket.service';
import { Platform } from '@angular/cdk/platform';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
})
export class UserLoginComponent implements OnDestroy {

  form: FormGroup;
  error = '';
  type = 0;
  loading = false;
  count = 0;
  interval$: any;
  _post: any = '';
  postList = [];

  constructor(fb: FormBuilder,
              private router: Router,
              public msg: ApesMessageService,
              private initService: InitService,
              private userAuthService: UserAuthService,
              private apiService: ApiService,
              private reuseTabService: ReuseTabService,
              private ws: WebsocketService,
              private platform: Platform) {

    this.checkPadLogin();

    this.form = fb.group({
      userName: ['', [Validators.required, Validators.minLength(5)]],     // czy01
      password: ['', Validators.required],        // 123456
      post: ['', [Validators.required]],
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
      remember: [false],
    });

  }

  /**
   * 功能：判断是否记住密码，如果记住密码就直接跳过登录
   */
  checkPadLogin() {

    if (this.platform.ANDROID) {
      const userInfo = this.userAuthService.getUserInfoLocalObj();
      if (userInfo && userInfo.userAccount) {
        const user = userInfo.userAccount;
        const userModel = { userId: user.userId, password: user.password, post: user.post };
        if(userModel.userId){
          this.sendLoginData(userModel);
        } else {
          this.msg.error('用户信息缺失，请退出重新登录！'); // 该用户已禁用，请联系行政人员
        }
      }
    }
  }

  get userName() {
    return this.form.controls.userName;
  }

  get password() {
    return this.form.controls.password;
  }

  get mobile() {
    return this.form.controls.mobile;
  }

  get post() {
    return this.form.controls.post;
  }

  get captcha() {
    return this.form.controls.captcha;
  }

  switch(ret: any) {
    this.type = ret.index;
  }

  // 获取验证码
  getCaptcha() {
    this.count = 59;
    this.interval$ = setInterval(() => {
      this.count -= 1;
      if (this.count <= 0)
        clearInterval(this.interval$);
    }, 1000);
  }

  _onUsernameBlur() {
    if (!this.userName.value) {
      return;
    }

    // 输入之后自动补0
    // let userNameStr = this.userName.value;
    // userNameStr = userNameStr.toString().padStart(7,'0');
    // this.form.patchValue({ userName: userNameStr});

    const userModel = { userId: this.userName.value };
    this.apiService.post('aut.user.getPosts', { 'body': JSON.stringify(userModel) }).subscribe(
      (body) => {
        if (body) {
          this.postList = body;

          this.form.patchValue({ post: this.postList[0] });
          this._post = this.postList[0];
        }
      });
  }

  select(param) {
    this._post = '';
    let index = param.selectedIndex - 1;
    this._post = this.postList[index];
  }

  check() {
    this.userName.markAsDirty();
    this.password.markAsDirty();
    let result = true;
    if (!this.userName.value) {
      this.error = '用户名不能为空';
      result = false;
      return result;
    }

    if (!this.form.value.post) {
      this.error = '岗位不能为空';
      result = false;
      return result;
    }

    if (!this.password.value) {
      this.error = '密码不能为空';
      result = false;
      return result;
    }
    return result;
  }

  login(): void {
    if (!this.check()) {
      return;
    }

    const userModel = {
      userId: this.userName.value,
      password: this.password.value,
      post: this._post,
    };

    if(userModel.userId){
      this.sendLoginData(userModel);
    } else {
      this.msg.error('用户信息缺失，请退出重新登录！'); // 该用户已禁用，请联系行政人员
    }
  }

  /**
   * 登录跳转方法
   * @param userModel
   */
  sendLoginData(userModel) {
    this.initService.loadI18n();
    this.apiService.post('aut.user.login', { 'body': JSON.stringify(userModel) })
      .subscribe((body) => {
        if(body) {
          const resultData = body.user;
          resultData['post'] = userModel.post;
          resultData['userId'] = userModel.userId;
          resultData['terminal'] = 'platformSystem';

          const userInfo = {'token': body.sessionId, 'userAccount': resultData,'terminal': 'platformSystem'};
          this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
          this.router.navigate(['']);

          // 清除复用路由导航
          this.reuseTabService.clear();
          this.ws.connect(userInfo.userAccount.id);
        }
      });
  }

  ngOnDestroy(): void {
    if (this.interval$) {
      clearInterval(this.interval$);
    }
  }
}
